package opensocial.data;

import java.sql.*;
import java.util.*;

import opensocial.data.basic.*;

import org.apache.shindig.social.core.model.*;
import org.apache.shindig.social.opensocial.model.*;
import org.apache.shindig.social.opensocial.spi.*;
import org.apache.shindig.social.opensocial.spi.GroupId.*;

import com.google.inject.*;

public class PersonDAOImpl implements PersonDAO {

  private DatabaseGateway gateway;
  
  @Inject
  public PersonDAOImpl(DatabaseGateway gateway){
    this.gateway = gateway;
  }
  
  @Override
  public Person getPerson(UserId id) {
    final Person person = new PersonImpl();
    
    gateway.executeQuery(
      "select * from people where id = " + id.getUserId(), 
      new ResultSetCommand(){
      public int work(ResultSet rs) throws SQLException {
        if(rs.next()){
          person.setName(new NameImpl());
          person.getName().setGivenName(rs.getString("name"));
          person.getName().setFamilyName(rs.getString("last_name"));
        }
        return 0;
      }
    });
    return person;
  }
  
  @Override
  public List<Person> getPeople(UserId id, GroupId gid) {
    if(gid.getType()!=(Type.friends)) return Collections.emptyList();
    
    final List<Person> group = new ArrayList<Person>();
    gateway.executeQuery( 
        "select p.name, p.last_name from people p, relations r where r.friend_id = p.id and r.person_id = " + id.getUserId(),
        new ResultSetCommand(){
        public int work(ResultSet rs) throws SQLException {
          while(rs.next()){
            Person p = new PersonImpl();
            p.setName(new NameImpl());
            p.getName().setGivenName(rs.getString("name"));
            p.getName().setFamilyName(rs.getString("last_name"));
            group.add(p);
          }
          return 0;
        }
    });
    return group;
  }
  
 
}
